using Microsoft.AspNetCore.Mvc;
using SmartideRepoList.Models;
using SmartideRepoList.Models.DTO;
using SqlSugar;

namespace SmartideRepoList.Controllers
{
    [ApiController]
    [Route("[controller]/[action]")]
    public class SmartIDEController : ControllerBase
    {
        private readonly ISqlSugarClient _sqlSugarClient;
        private readonly IConfiguration _configuration;
        private readonly ILogger<SmartIDEController> _logger;

        public SmartIDEController(ILogger<SmartIDEController> logger, ISqlSugarClient sqlSugarClient, IConfiguration configuration)
        {
            _logger = logger;
            this._sqlSugarClient = sqlSugarClient;
            this._configuration = configuration;
        }

        [HttpGet(Name = "getAll")]
        public async Task<string> GetAll()
        {
            try
            {
                return await new Utils.ApiUtil().GetProjects(this._configuration);
            }
            catch (Exception ex)
            {
                this._logger.LogError(ex.Message);
                return @"{""msg"":""invoke the api error""}";
            }
        }

        [HttpGet(Name = "getAllDb")]
        public async Task<ActionResult> GetAllDb()
        {
            try
            {
                var left = await _sqlSugarClient.Queryable<TableLeft>().ToArrayAsync();
                var right = await _sqlSugarClient.Queryable<TableRight>().ToArrayAsync();
                return new JsonResult(new Data { LeftProjects = left, RightProjects = right });
            }
            catch (Exception ex)
            {
                this._logger.LogError(ex.Message);
                return new JsonResult(new { msg = "get db data error" });
            }
        }

        [HttpPost(Name = "Update")]
        public async Task<bool> UpdateData([FromBody] UpdateModel model)
        {
            Guid[] ids = model.Ids;
            if (ids == null || ids.Length == 0)
            {
                return false;
            }
            bool toRight = model.IsRight;
            _sqlSugarClient.Ado.BeginTran();
            try
            {
                if (toRight)
                {
                    var left = await _sqlSugarClient.Queryable<TableLeft>().Where(l => ids.Contains(l.Id)).ToListAsync();
                    if (left is null)
                    {
                        return false;
                    }
                    await _sqlSugarClient.Deleteable(left).ExecuteCommandAsync();
                    var right = new List<TableRight>();
                    foreach (var item in left)
                    {
                        right.Add(new TableRight
                        {
                            Id = item.Id,
                            Name = item.Name
                        });
                    }
                    await _sqlSugarClient.Insertable<TableRight>(right).ExecuteCommandAsync();
                    _sqlSugarClient.Ado.CommitTran();
                    return true;
                }
                else
                {
                    var right = await _sqlSugarClient.Queryable<TableRight>().Where(l => ids.Contains(l.Id)).ToListAsync();
                    if (right is null)
                    {
                        return false;
                    }
                    await _sqlSugarClient.Deleteable(right).ExecuteCommandAsync();
                    var left = new List<TableLeft>();
                    foreach (var item in right)
                    {
                        left.Add(new TableLeft
                        {
                            Id = item.Id,
                            Name = item.Name
                        });
                    }
                    await _sqlSugarClient.Insertable(left).ExecuteCommandAsync();
                    _sqlSugarClient.Ado.CommitTran();
                    return true;
                }
            }
            catch (Exception ex)
            {
                _sqlSugarClient.Ado.RollbackTran();
                _logger.LogError(ex.Message);
                return false;
            }

        }

    }


}